package cc.eddic.pratice.programmingparadigms.emp02list.impl;

import cc.eddic.pratice.programmingparadigms.Employee;
import cc.eddic.pratice.programmingparadigms.EmployeeComparator;
import cc.eddic.pratice.programmingparadigms.EmployeePredicate;
import cc.eddic.pratice.programmingparadigms.emp02list.EmployeeList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EmployeeListLxImpl implements EmployeeList {
    private static final Logger log = LoggerFactory.getLogger(ResultListGcsImpl.class);
    private Employee[] employees;
    private int index;

    public EmployeeListLxImpl(int capacity){employees = new Employee[capacity];}
    @Override
    public void add(Employee employee) {
        if(index==employees.length){
            Employee[] newEmployees = new Employee[employees.length*2];
            System.arraycopy(employees, 0, newEmployees, 0, size());
            employees = newEmployees;
            employees[index]=employee;
            index++;
            if (log.isDebugEnabled()) log.debug("超出数组长度，进行扩容长度为 {}！！",employees.length);
        }else{
            if (log.isDebugEnabled()) log.debug("{} {} {} {}", employee.getName(), employee.getGender(),employee.getJobTitle(),employee.getJobTitle());
            employees[index]=employee;
            index++;
        }
    }

    @Override
    public Employee get(int index) {
        if (index < 0 || index >= size()) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size());
        }
        return employees[index];
    }

    @Override
    public int size() {
        return index;
    }
    @Override
    public Employee find(EmployeePredicate predicate) {
        for(int i=0;i<size();i++){
            Employee e = get(i);
            if(predicate.test(e)){
                return e;
            }
        }
        return null;
    }

    @Override
    public void sort(EmployeeComparator comparator) {
        for(int i=0;i<size();i++){
            for(int j=i;j<size();j++){
                if(comparator.compare(employees[j],employees[j+1])>0){
                    Employee temp = employees[j];
                    employees[j] = employees[j+1];
                    employees[j+1]=temp;
                }
            }
        }
    }
}
